package com.taotao.manage.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.mapper.Mapper;
import com.taotao.common.service.RedisService;
import com.taotao.manage.pojo.ItemDesc;

@Service
public class ItemDescService extends BaseService<ItemDesc> {

	@Autowired
	private Mapper<ItemDesc> mapper;

	@Autowired
	private PropertiesService propertiesService;

	@Autowired
	private RedisService shardedJedisPoolService;

	public ItemDesc queryItemById(Long itemId) {
		//0、查看缓存中是否已经有数据，命中缓存则直接返回，没有命中则查询数据库，最后将数据存储到缓存中
		//缓存机制一定不能影响程序正常运行，所以需要捕获异常
		String str = propertiesService.REDIS_ITEMDESC_ID;
		String key = StringUtils.replace(str, "{ID}", itemId.toString());
		try {
			//获取缓存
			String redisResult = shardedJedisPoolService.get(key);
			if (StringUtils.isNotEmpty(redisResult)) {
				//命中缓存后转换成对象返回
				return PropertiesService.MAPPER.readValue(redisResult, ItemDesc.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		//1.缓存中没有，就去数据库查询商品
		ItemDesc itemDescResult = mapper.selectByPrimaryKey(itemId);

		//2.将查询到的所有商品类目信息存储到缓存中

		try {
			String value = PropertiesService.MAPPER.writeValueAsString(itemDescResult);
			int time = Integer.parseInt(propertiesService.REDIS_ITEMDESC_ID_TIME);
			shardedJedisPoolService.setex(key, time, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return itemDescResult;
	}

}
